package cn.edu.xmu.server.service;

import cn.edu.xmu.server.controller.WebSocketController;
import cn.edu.xmu.server.dao.bo.ChatMsg;
import cn.edu.xmu.server.util.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ReceiveService {
    private final static Logger logger = LoggerFactory.getLogger(SendService.class);

    public void handleMsg(ChatMsg chatMsg) {

        logger.info("msg = {}",chatMsg);
        ConcurrentHashMap<String, Session> sessionPool = WebSocketController.getSessionPool();

        if(Objects.equals(chatMsg.getType(), ChatMsg.SINGLE_CHAT)) {
            logger.info("websocket: receive_id = {}", chatMsg.getReceiver());
            sendMessage(chatMsg,chatMsg.getReceiver(),sessionPool);
        }

        else if(Objects.equals(chatMsg.getType(), ChatMsg.GROUP_CHAT)){
            List<String> userList=new ArrayList<>();
            //todo：从数据库 redis中获取这个群聊的userId
            for (String receiverId:userList) {
                sendMessage(chatMsg,receiverId,sessionPool);
            }

        }
    }

    private void sendMessage(ChatMsg chatMsg,String receiverId ,ConcurrentHashMap<String, Session> sessionPool) {
        if (sessionPool.containsKey(chatMsg.getReceiver())) {
            Session receiverSession = sessionPool.get(chatMsg.getReceiver());
            ChatMsg msg = ChatMsg.builder().sender(chatMsg.getSender())
                    .receiver(chatMsg.getReceiver())
                    .group_id(chatMsg.getGroup_id())
                    .type(chatMsg.getType())
                    .message(chatMsg.getMessage()).build();
            receiverSession.getAsyncRemote().sendText(JacksonUtil.toJson(msg));
        }
    }
}
